module ExternalRssTags
  include Radiant::Taggable
  
  desc %{  Tag encapsulating the RSS namespace of tags.}
  tag "rss" do |tag|
    tag.expand
  end
  
  desc %{  Tag representing all RSS feeds collectively.}
  tag "rss:feeds" do |tag|
    tag.locals.rss_feeds = ExternalRssFeed.find(:all)
    
    tag.expand
  end
  
  desc %{  Tag providing iteration over all RSS feeds.}
  tag "rss:feeds:each" do |tag|
    result = []
    
    feeds = tag.locals.rss_feeds
    
    feeds.each do |feed|
      if feed.valid?
        tag.locals.rss_feed = feed
      
        result << tag.expand
      end
    end
    
    result
  end
  
  desc %{  Tag encapsulating a single RSS feed. Selection of a feed will either
           be handled automatically or explicitly via the name attribute.
        }
  tag "rss:feed" do |tag|
    tag.locals.rss_feed = tag.attr['name'].blank? ? tag.locals.rss_feed : tag.attr['name']
    
    if tag.locals.rss_feed.valid?
      tag.expand
    else
      raise TagError, "The RSS Feed \"#{tag.locals.rss_feed.name}\" is not valid."
    end
  end
  
  desc %{  Returns the title of a given feed.}
  tag "rss:feed:title" do |tag|
    raise TagError, "No RSS feed context found." unless tag.locals.rss_feed
    
    tag.locals.rss_feed.title
  end
  
  desc %{  Returns the link for a given feed.}
  tag "rss:feed:link" do |tag|
    raise TagError, "No RSS feed context found." unless tag.locals.rss_feed
    
    tag.locals.rss_feed.link
  end
  
  desc %{  Returns the description of a given feed.}
  tag "rss:feed:description" do |tag|
    raise TagError, "No RSS feed context found." unless tag.locals.rss_feed
    
    tag.locals.rss_feed.description
  end
  
  desc %{  Tag encapsulating all the items within a feed.}
  tag "rss:feed:items" do |tag|
    tag.locals.rss_feed_items = tag.locals.rss_feed.items
    
    tag.expand
  end
  
  desc %{  Tag providing iteration over all items in a feed.}
  tag "rss:feed:items:each" do |tag|
    result = []

    items = tag.locals.rss_feed_items
    
    items.each do |item|
      tag.locals.rss_feed_item = item
    
      result << tag.expand
    end
    
    result
  end
  
  desc %{  Tag ecnapsulating a single item within a feed.}
  tag "rss:feed:item" do |tag|
    tag.expand
  end
  
  desc %{  Returns the title of a given item.}
  tag "rss:feed:item:title" do |tag|
    tag.locals.rss_feed_item.title
  end
  
  desc %{  Returns the link of a given item.}
  tag "rss:feed:item:link" do |tag|
    tag.locals.rss_feed_item.link
  end
  
  desc %{  Returns the description of a given item.}
  tag "rss:feed:item:description" do |tag|
    tag.locals.rss_feed_item.description
  end
end